window.SQLITE = {
	openDatabase: function (db_name) {
		if (plus.sqlite.isOpenDatabase({
			name: db_name,
			path: '_doc/' + db_name + '.db'}) == false) {
			plus.sqlite.openDatabase({
				name: db_name,
				path: '_doc/' + db_name + '.db',
				success: function(e){
					console.log("open db succeed: " + JSON.stringify(e));
				},
				fail: (e) => {
					console.log("failed to open database: " + JSON.stringify(e));
				}
			});
		}
	},
	
	insertChatMsg: function (from, to, content) {
		SQLITE.openDatabase('chat');
		plus.sqlite.executeSql({
			name: 'chat',
			sql: 'CREATE TABLE IF NOT EXISTS chat_msg('
				+ '"from" VARCHAR(20), "to" VARCHAR(20), "msg" VARCHAR(1000), "ts" TIMESTAMP DEFAULT CURRENT_TIMESTAMP)',
			success: () => {
				console.log("create table succeed!");
				plus.sqlite.executeSql({
					name: 'chat',
					sql: "INSERT INTO chat_msg('from', 'to', 'msg') VALUES ('" + from + "','" + to + "','" + content + "')",
					success: () => {
						console.log('insert record succeed!');
					},
					fail: (e) => {
						console.log('insert record failed!' + JSON.stringify(e));
					}
				});
			},
			fail: (e) => {
				console.log("create table failed: " + JSON.stringify(e));
			}
		});
	},
	
	selectChatMsg: function (myId, friendId, pageIndex, pageSize, callback) {
		var condition1 = '"from" IN(' + myId + ',' + friendId + ')';
		var condition2 = '"to" IN(' + myId + ',' + friendId + ')';
		SQLITE.openDatabase('chat');
		plus.sqlite.selectSql({
			name: 'chat',
			sql: 'SELECT * FROM chat_msg'
				+ ' WHERE ' + condition1 + ' AND ' + condition2
				+ ' ORDER BY ts DESC LIMIT ' + pageSize + ' OFFSET '
				+ pageSize * (pageIndex - 1),
			success: (data) => callback(data),
			fail: (e) => console.log("select table failed: " + JSON.stringify(e))
		});
	}
}